package cn.timelost.qy.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {

    private static final CopyOnWriteArraySet<WebSocketServer> connections = new CopyOnWriteArraySet<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        connections.add(this);
        log.info("新建连接: " + session.getId());
    }

    @OnClose
    public void onClose() {
        connections.remove(this);
        log.info("连接关闭: " + session.getId());
    }

    @OnError
    public void onError(Session session, Throwable t) {
        log.info("异常情况处理:" + session.getId());
        try {
            boolean open = session.isOpen();
            if (open) {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        log.error(t.getMessage(), t);
    }

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void broadcast(String message) {
        for (WebSocketServer client : connections) {
            client.sendMessage(message);
        }
    }

}
